package com.osilon.updater.tasks;

import java.util.List;

import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodNode;

import com.osilon.asm.InsnSearcher;
import com.osilon.asm.OsilonClassNode;
import com.osilon.asm.OsilonMethodNode;
import com.osilon.util.ClassCache;
import com.sun.xml.internal.ws.org.objectweb.asm.Opcodes;

public class ItemTask extends Task {
	@Override
	public boolean canProcess(OsilonClassNode node) {
		return node.constants.get("Count") != null;
	}

	@Override
	public void process(ClassCache cache, OsilonClassNode node) {
		node.interfaces.add("com/osilon/hooks/Item");
		
		List<OsilonMethodNode> methods = node.constants.get("Count");
		
		MethodNode mn = null;
		
		for(MethodNode m : methods) {
			InsnSearcher s = new InsnSearcher(m);
			
			if(s.nextFieldInsn(Opcodes.PUTFIELD) == null) {
				mn = m;
				break;
			}
		}
		
		InsnSearcher s = new InsnSearcher(mn);
		LdcInsnNode insn;
		
		while((insn = s.nextLdc()) != null) {
			String name = insn.cst.toString();
			FieldInsnNode fin = s.nextFieldInsn(Opcodes.GETFIELD);
			
			node.addGetter("get" + ((Character.toUpperCase(name.charAt(0)) + name.substring(1))), fin.desc, fin.name, fin.desc);
			node.addSetter("set" + ((Character.toUpperCase(name.charAt(0)) + name.substring(1))), fin.desc, fin.name, fin.desc);
		}
	}
}
